#! /usr/bin/env python
import os
import sys
import urllib
import urllib2
from optparse import OptionParser

'''This script takes a list of directories which take .dat files that are the
   airfoil designs and uploads them to the server.'''

''' ajray changed it to take a list of files instead '''



def upload(filename, data, url):
    d = {
        'filename': filename,
        'data'    : data
    }

    print 'uploading', filename
    req = urllib2.Request(url+"/upload", urllib.urlencode(d))
    f = urllib2.urlopen(req)
    return f.read()

def visit(url, dirname, names):
    for name in names:
        bname, ext = os.path.splitext(name)
        if ext == ".dat":
            # We need to trim off the final new line since it will screw up the
            # parsing server-side
            contents = open(os.path.join(dirname, name), "r").read()[:-1]
            try:
                response = upload(name, contents, url)
                print response
            except urllib2.URLError, e:
                print e.read()
            return


if __name__ == "__main__":
    parser = OptionParser(usage="usage: %prog [options] [dirs...]")
    parser.add_option("-u", "--url", dest="url", default="http://localhost:8080",
                      help="The URL to upload the airfoil designs to. If not set,"
                           "it defaults to localhost:8080")
    (options, args) = parser.parse_args()
    if len(args) < 1:
        parser.print_help()
        exit(1)

    for filename in args:
        f = open(filename)
        upload(filename,f.read(),options.url)
        f.close()
        #os.path.walk(d, visit, options.url)
